from django.shortcuts import render
from django.views import View
from meiduo_mall.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django import http
from meiduo_mall.utils.response_code import RETCODE
import random
from meiduo_mall.libs.yuntongxun.sms import CCP
from celery_tasks.sms.tasks import send_sms


class ImagecodeView(View):
    def get(self,request,uuid):
        text,code,image = captcha.generate_captcha()

        redis_cli=get_redis_connection('verify_code')
        redis_cli.setex(uuid,constants.IMAGE_CODE_EXPIRES,code)
        return http.HttpResponse(image,content_type='image/png')

class SmscodeView(View):
    def get(self,request,mobile):
        image_code_request=request.GET.get('image_code')
        uuid=request.GET.get('image_code_id')

        redis_cli=get_redis_connection('verify_code')
        image_code_redis = redis_cli.get(uuid)


        if not image_code_redis:
            return http.JsonResponse({
                'code':RETCODE.PARAMERR,
                'errmsg':'图形验证码已过期'
            })



        redis_cli.delete(uuid)

        if image_code_redis.decode() != image_code_request.upper():
            return http.JsonResponse({
                'code':RETCODE.PARAMERR,
                'errmsg':'图形验证码错误'
            })
        if redis_cli.get('sms_flag_'+mobile):
            return http.JsonResponse({
                'code': RETCODE.PARAMERR,
                'errmsg': '已经向此手机号发过短信，请查看手机'
            })
        sms_code = '%06d' % random.randint(0, 999999)

        # redis_cli.setex('sms_' + mobile, constants.SMS_CODE_EXPIRES, sms_code)
        # redis_cli.setex('sms_flag_'+mobile,constants.SMS_CODE_FLAG_EXPIRES,1)
        redis_pl=redis_cli.pipeline()
        redis_pl.setex('sms_'+mobile,constants.SMS_CODE_EXPIRES,sms_code)
        redis_pl.setex('sms_flag_'+mobile,constants.SMS_CODE_FLAG_EXPIRES,1)
        redis_pl.execute()
        # ccp=CCP()
        # ret = ccp.send_template_sms(mobile,[sms_code,constants.SMS_CODE_EXPIRES / 60],1 )
        # print(sms_code)
        send_sms.delay(mobile,[sms_code,constants.SMS_CODE_EXPIRES / 60],1 )

        return http.JsonResponse({
            'code':RETCODE.OK,
            'errmsg':"OK"
        })




